package com.ibeetl.eval.worker;

import java.util.List;

import org.jdom2.Element;

import com.ibeetl.eval.EvalContext;
import com.ibeetl.eval.NodeWorker;
import com.ibeetl.eval.TreeNode;
/**
 * 决策节点，第一个子节点逻辑表达式是，第二个节点是true的时候返回的结果，第三个是false的时候返回的结果
 * 第三个节点可以是决策节点
 * @author xiandafu
 *
 */
public class SimpleDecisionNodeWorker implements NodeWorker {

	public  TreeNode execute(Element ruleEle,EvalContext ctx){
		String name = ruleEle.getAttributeValue("name");
		TreeNode node =  ctx.enter(name, ruleEle);
		List<Element> list = ruleEle.getChildren();
		
		Element condtionEle  = list.get(0);
		Element trueEle = null;
		Element falseEle = null;
		if(list.size()==3){
			 trueEle= list.get(1);
			 falseEle = list.get(2);
		}else if(list.size()==2){
			 trueEle = null;
			 falseEle = list.get(1);
		}else{
			 trueEle = null;
			 falseEle = null;
		}
			
		
		TreeNode condtionNode = ctx.getEvalEngine().processRule(condtionEle, ctx);
		Object ret = condtionNode.getResult();
		if(ret instanceof Boolean &&((Boolean)ret) ){
			//true 分支
			if(trueEle!=null){
				TreeNode trueNode = ctx.getEvalEngine().processRule(trueEle, ctx);
				node.setResult(trueNode.getResult());
			}else{
				node.setResult(Boolean.TRUE);
			}
			
			
		}else{
			if(falseEle!=null){
				TreeNode falseNode = ctx.getEvalEngine().processRule(falseEle, ctx);
				node.setResult(falseNode.getResult());
			}else{
				node.setResult(Boolean.FALSE);
			}
			
		}
		
		ctx.exist();
		return node;
	}
	
}
